package com.open.capacity.user.service.impl;

import com.open.capacity.commons.Result;
import com.open.capacity.prints.util.uuid.UUIDUtils;
import com.open.capacity.user.dao.SysUserRelationDao;
import com.open.capacity.user.model.SysUserRelation;
import com.open.capacity.user.service.SysUserRelationService;
import com.open.capacity.user.vo.SysUserRelationVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class SysUserRelationServiceImpl implements SysUserRelationService {

    @Autowired
    private SysUserRelationDao sysUserRelationDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SysUserRelation sysUserRelation) {
        sysUserRelation.setCreateTime(new Date());

        sysUserRelationDao.save(sysUserRelation);
        log.info("保存用户关联：{}", sysUserRelation);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByObjectId(String objectId) {

        sysUserRelationDao.deleteByObjectId(objectId);

        log.info("删除用户关联：{}", objectId);
    }


    @Override
    public List<SysUserRelation> findByObjectId(String objectId) {
        return sysUserRelationDao.findByObjectId(objectId);
    }

    @Override
    public List<SysUserRelation> findByUserId(String userId) {
        return sysUserRelationDao.findByUserId(userId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveOrUpdate(SysUserRelationVo sysUserRelation) {

        sysUserRelationDao.deleteByObjectId(sysUserRelation.getObjectId());
        Date now = new Date();

        if (!CollectionUtils.isEmpty(sysUserRelation.getUserIds())) {
            sysUserRelation.getUserIds().forEach(u -> {
                SysUserRelation model = new SysUserRelation();
                model.setId(UUIDUtils.getOriginalUUIDWithoutBar());
                model.setObjectType(sysUserRelation.getObjectType());
                model.setObjectId(sysUserRelation.getObjectId());
                model.setUserId(u);
                model.setCreateTime(now);
                sysUserRelationDao.save(model);
            });
        }

        return 1 > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }
}
